import numpy as np
import matplotlib.pyplot as plt
"""
PCA算法进行主特征提取
"""
def PCA(X):
    """
    零均值化
    :param X: 输入的矩阵
    :return: X_afte_mean,是去均值化后的矩阵
    """
    [m,n]=np.shape(X)
    x_mean=[]
    for x in X:
        x_mean.append( np.mean(x))
    X_after_mean=[]
    for ii in range(len(X)):
        X_after_mean_temp=[]
        for i in range(len(X[ii])):
            X_after_mean_temp.append(X[ii][i]-x_mean[ii])
        X_after_mean.append(X_after_mean_temp)

    """
    求协方差矩阵
    :return cov_X_after_mean就是协方差矩阵
    """
    X_after_mean=np.matrix(X_after_mean)
    cov_X_after_mean=X_after_mean*np.matrix(np.transpose(X_after_mean))/n
    # print(cov_X_after_mean)
    print(np.shape(cov_X_after_mean))
    """
    求协方差矩阵对应的特征值和特征向量
    """
    [eig,feature_vector]=np.linalg.eig(cov_X_after_mean)
    max_index_eig=0
    max_eig=np.sort(eig)[-1]
    for index in range(0, len(eig)):
        if eig[index] ==max_eig:
            max_index_eig=index
    result_pca=np.matrix(feature_vector[max_index_eig])*X_after_mean
    # print('max_eig is:%f\n' %max_eig)
    # print('max_eig_index is:%d\n' %max_index_eig)
    # print('eig is:\n{}'.format(eig))
    # print('feature_vector is:\n{}'.format(feature_vector))
    # print('result of pca:\n{}'.format(result_pca))
    return result_pca

if __name__=="__main__":
    X=[[1,1,2,4,2],[1,3,3,4,4]]
    Y=[[2,-3,1],[1,-2,1],[1,-3,2]]
    pca_result=PCA(X)
    # plt.plot(-pca_result)
    # plt.show()